package com.zmh.common;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import jp.sourceforge.qrcode.QRCodeDecoder;
import jp.sourceforge.qrcode.data.QRCodeImage;
import jp.sourceforge.qrcode.exception.DecodingFailedException;

/**
 * @author zhoumh
 * @version 创建时间：2018年4月5日 上午11:51:40
 * @Description
 */
@Service
public class QRCodeHandler {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	/**
	 * 
	 * 解析二维码（QRCode）
	 * 
	 * @param input 输入流
	 * @return String
	 * @author zhoumh
	 * @version 创建时间：2018年4月5日 下午5:42:49
	 */
	public String decoderQRCode(String imgPath) {
		// QRCode 二维码图片的文件
		File imageFile = new File(imgPath);

		BufferedImage bufImg = null;
		String decodedData = null;
		try {
			bufImg = ImageIO.read(imageFile);
			QRCodeDecoder decoder = new QRCodeDecoder();
			decodedData = new String(decoder.decode(new J2SEImage(bufImg)));
		} catch (IOException e) {
			logger.error("Error: " + e.getMessage());
			e.printStackTrace();
		} catch (DecodingFailedException dfe) {
			logger.error("Error: " + dfe.getMessage());
			dfe.printStackTrace();
		}
		return decodedData;
	}

	class J2SEImage implements QRCodeImage {
		BufferedImage bufImg;

		public J2SEImage(BufferedImage bufImg) {
			this.bufImg = bufImg;
		}

		public int getWidth() {
			return bufImg.getWidth();
		}

		public int getHeight() {
			return bufImg.getHeight();
		}

		public int getPixel(int x, int y) {
			return bufImg.getRGB(x, y);
		}

	}

}
